#pragma once

#include "../http/httpserver/HTTPServer.h"
#include "../websocket/server/Upgrader.h"
#include "../websocket/server/WebsocketManger.h"
#include <thread>

int scount = 0;

inline void ws_server_example(const std::string& ip, const TLSConfigPtr& tls)
{
    HTTPServer svr;

    WebsocketManger mgr;
    mgr.set_open_handle([](const WebsocketConnPtr& conn) {
        printf("wsserver connect success remote:%s local:%s\n",
            conn->remote_addr_string().c_str(), conn->local_addr_string().c_str());
    });
    mgr.set_message_handle([](const WebsocketConnPtr& c, WebsocketFramePtr msg) {
        //printf("server recv: %s\n", msg->payload().c_str());
        scount++;
        c->write(OPCODE::text, msg->payload());

    });
    mgr.set_close_handle([](const WebsocketConnPtr& c, const std::error_code& e) {
        printf("peer close\n");
    });

    svr.register_handle<HTTPMethod::REQ_GET>("/ws", [&](RequestPtr r, ResponseWriterPtr rw) {
        std::error_code ec = mgr.upgrade(r, rw);
        if (ec) {
            printf("%s\n", ec.message().c_str());  
            return;
        }
        printf("upgrade success\n");
    });
    svr.register_handle("/http", [&](RequestPtr r, ResponseWriterPtr rw) {
        rw->write(HTTPStatus::StatusOK, r->Body);
    });
    auto ec = svr.listen(ip, tls);
    if (ec) {
        printf("listen:%s\n", ec.message().c_str());
    }
    svr.run();

    getchar();
    svr.stop();
}